from fastapi import FastAPI
from fastapi.requests import Request
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware

from utils.g import G
from utils.helper import generate_uuid
from utils.logger import thread_logger
from utils.enums import Language


def register_middleware(app: FastAPI, secret_key: str):
    # CORS限制
    app.add_middleware(
        CORSMiddleware,  # type: ignore  # 跨域中间件
        allow_origins=["*"],  # 允许跨域访问的域名
        allow_credentials=True,  # 允许携带cookie
        allow_methods=["*"],  # 允许跨域访问的方法
        allow_headers=["*"],  # 允许跨域访问的请求头
    )

    # 加密会话数据的密钥
    app.add_middleware(SessionMiddleware, secret_key=secret_key)  # type: ignore

    # 注册请求ID、日志控制器、语言、以及全局变量初始化工作
    @app.middleware("http")
    async def register(request: Request, call_next):
        # 注册请求ID
        request.state.request_id = generate_uuid()

        # 注册请求日志
        request.state.logger = thread_logger(thread_id=request.state.request_id)

        # 注册语言
        language = request.cookies.get("language", Language.CN.value)
        if language == Language.CN.value:
            language = Language.CN
        else:
            language = Language.EN
        request.state.language = language

        # 注册站点信息
        request.state.site_info = await G.get_site_info(language)

        # 注册产品列表信息
        request.state.product_type_list = await G.get_product_type_list(language)

        # 注册新闻列表信息
        request.state.news_type_list = await G.get_news_type_list(language)

        # 注册最新5条新闻信息
        request.state.nestest_news_items = await G.get_newest_news(language)

        response = await call_next(request)
        return response
